package cn.wolfcode.luowowo.interceptor;

import cn.wolfcode.luowowo.util.JsonResult;
import cn.wolfcode.luowowo.util.Md5Utils;
import com.alibaba.fastjson.JSON;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

import static com.sun.deploy.util.ArrayUtil.arrayToString;

/**
 * 签名拦截(防篡改)
 */
public class SignInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        //签名验证
        // 获取前端传过来所有的参数,封装成map
        /**
         * aa:["1"]
         * bb:["2"]
         * cc:["3"]
         * dd:["4"]
         * sign:["sdfsdfsdf"] 加密过后的签名值
         */
        Map<String, String[]> map = request.getParameterMap();
        Map<String, Object> param = new HashMap<>();
        for (String s : map.keySet()) {
            if ("sign".equalsIgnoreCase(s)) {
                continue;
            }
            /**
             * aa:"1"
             * bb:"2"
             * cc:"3"
             * dd:"4"
             * sign:"sdfsdfsdf"加密过后的签名值
             */
            param.put(s, arrayToString(map.get(s)));
        }
        String signatures = Md5Utils.signatures(param);// 服务端通过MD5算法得出的签名sign_service
        String sign = request.getParameter("sign");// 页面上传过来的签名sign_client
        if (sign == null || !sign.equalsIgnoreCase(signatures)) {
            response.setContentType("text/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(new JsonResult(501, "签名校验失败", "不好意思咯")));
            return false;
        }
        return true;
    }

    private String arrayToString(String [] array){

        StringBuilder sb = new StringBuilder(10);
        for (String s : array) {
            sb.append(s);
        }

        return sb.toString();
    }
}